//
//  YDYQRCodeViewController.m
//  DY_Weibo3
//
//  Created by 杨德勇 on 2016/8/19.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

#import "YDYQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface YDYQRCodeViewController ()<UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
/*顶部工具条*/
@property (weak, nonatomic) IBOutlet UITabBar *tabbar;
/*冲击波顶部约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scanTopLayout;
/*容器高度约束*/
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containHeightLayout;
/*容器*/
@property (weak, nonatomic) IBOutlet UIView *container;

/** 二维码画图用的layer */
@property (nonatomic, strong) CALayer *drawRectLayer;
/** 二维码扫描输入 */
@property (nonatomic, strong) AVCaptureDeviceInput *input;
/** 二维码扫描输出 */
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
/** 二维码扫描会话 */
@property (nonatomic, strong)  AVCaptureSession *session;
/** 二维码扫描预览 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@end

@implementation YDYQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tabbar.selectedItem = self.tabbar.items.firstObject;
    self.tabbar.delegate = self;
}
-(void)viewDidAppear:(BOOL)animated{
    
    [self startScanAnimation];
    [self startScan];
}

-(void)startScanAnimation{
    self.scanTopLayout.constant = - self.containHeightLayout.constant;
    [self.view layoutIfNeeded];
    
    [UIView animateWithDuration:2.0 animations:^{
        [UIView setAnimationRepeatCount:MAXFLOAT];
        self.scanTopLayout.constant = self.containHeightLayout.constant;
        [self.view layoutIfNeeded];
    }];
    
}
-(void)startScan{
    if (![self.session canAddInput:self.input])return;
    if (![self.session canAddOutput:self.output])return;
    
    [self.session addInput:self.input];
    [self.session addOutput:self.output];
    self.output.metadataObjectTypes = self.output.availableMetadataObjectTypes;
    [self.output setMetadataObjectsDelegate:self  queue:dispatch_get_main_queue()];
    //把预览图层放后面
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    self.previewLayer.frame = self.view.bounds;
    //加入画图用的layer
    [self.view.layer addSublayer:self.drawRectLayer];
    self.drawRectLayer.frame = self.view.bounds;
    
    [self.session startRunning];
}

#pragma mark -
#pragma mark -AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects.count == 0){
        //解决：移开镜头，二维码框不消失
        [self clearDrawLayer];
        return;
    }
    //1.绘图
    
    [self drawRect:metadataObjects.lastObject] ;
    
    
}
-(void)drawRect:(AVMetadataMachineReadableCodeObject *)objc{
    [self clearDrawLayer];
    if (objc == nil)return;
    
    AVMetadataMachineReadableCodeObject *tramsformedObjc = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:objc];
    
    NSArray *conners = tramsformedObjc.corners;
    
    CAShapeLayer *layer = [[CAShapeLayer alloc]init];
    layer.lineWidth = 3.0;
    layer.fillColor = [[UIColor clearColor]CGColor];
    layer.strokeColor = [[UIColor greenColor]CGColor];
    
    int i = 0;
    
    CFDictionaryRef dict = (__bridge CFDictionaryRef)(conners[i++]);
    CGPoint point = CGPointZero;
    CGPointMakeWithDictionaryRepresentation(dict, &point);
    
    UIBezierPath *path = [[UIBezierPath alloc]init];
    [path moveToPoint:point];
    
    
    
    while (i< conners.count) {
         dict = (__bridge CFDictionaryRef)(conners[i++]);
         CGPointMakeWithDictionaryRepresentation(dict, &point);
         [path addLineToPoint:point];
        
    }
    [path closePath];
    layer.path = path.CGPath;
    [self.drawRectLayer addSublayer:layer];
    
}
-(void)clearDrawLayer{
    for (CALayer *layer in self.drawRectLayer.sublayers) {
        [layer removeFromSuperlayer];
    }
}
#pragma mark -
#pragma mark -点击事件
- (IBAction)cancle:(UIBarButtonItem *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)openPhoto:(UIBarButtonItem *)sender {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])return;
    
    UIImagePickerController *imgPickController = [[UIImagePickerController alloc]init];
    imgPickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgPickController.delegate = self;
    [self presentViewController:imgPickController animated:YES completion:nil];
}

#pragma mark -
#pragma mark -工具栏点击事件
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    if ([item.title isEqualToString:@"二维码"]) {
        self.containHeightLayout.constant = 300;
    }else if ([item.title isEqualToString:@"条形码"]){
        self.containHeightLayout.constant = 200;
    }
//    [self.view layoutIfNeeded];
    [self.container.layer removeAllAnimations];
    [self startScanAnimation];
}

#pragma mark -
#pragma mark -Image pick view controller delegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
    UIImage *image = (UIImage *)info[UIImagePickerControllerOriginalImage];
    if (image == nil) return;
    //用探测器探测
    CIImage *ciImage = [[CIImage alloc]initWithImage:image];
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:nil];
    NSArray *results = [detector featuresInImage:ciImage];

    //取出探测到的数据
    for (CIQRCodeFeature *result in results) {
        
        }
    
   
    
}
#pragma mark -
#pragma mark -懒加载
-(AVCaptureDeviceInput *)input{
    if (_input== nil) {
        
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        _input = [[AVCaptureDeviceInput alloc]initWithDevice:device error:nil];
    }
    
    return _input;
}
-(AVCaptureMetadataOutput *)output{
    if (_output == nil) {
        _output = [[AVCaptureMetadataOutput alloc]init];
    }
    
    return _output;
}
-(AVCaptureSession *)session{
    if (_session == nil) {
        _session =[[AVCaptureSession alloc]init];
        
    }
    return _session;
}
-(AVCaptureVideoPreviewLayer *)previewLayer{
    if (_previewLayer == nil) {
        _previewLayer =[[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session] ;
    }
    return _previewLayer;
}
-(CALayer *)drawRectLayer{
    if (_drawRectLayer == nil) {
        _drawRectLayer = [[CALayer alloc]init];
        
    }
    return _drawRectLayer;
}
@end
